package sv.com.renacempleo.web.controller.red;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import sv.com.renacempleo.dto.red.RedEmpresas;
import sv.com.renacempleo.exception.WebException;
import sv.com.renacempleo.web.controller.BaseController;
import sv.com.renacempleo.web.security.CustomUser;
import sv.com.renacempleo.web.util.DBContext;
import sv.com.renacempleo.web.util.WebUtilidades;

@SuppressWarnings("serial")
@Controller
@RequestMapping("/admin/empresas")
public class RedEmpresasController extends BaseController{

	@RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
	public String view(ModelMap model, 
			@RequestParam (required = false) String header) {
		model.addAttribute(WebUtilidades.HEADER_TITLE, StringUtils.isBlank(header) ? "EMPRESAS" : header);
		try {
			model.put("ctgMediosBusqueda", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllByCodigoAsArray(WebUtilidades.CTG_MEDIOS_BQD_EMPLEO_PADRE)));
			model.put("ctgOficinas", JSONArray.fromObject(DBContext.getCtgOficinasDao().findAllActivesAsArray()));
			model.put("sgdUsuario", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllActivesAsArray()));
			model.put("data", JSONArray.fromObject(DBContext.getRedEmpresasDao().findAllInactivesAsArray()));
		} catch (WebException e) {
			logger.error("Exception:", e);
		}
		return "red/empresas/redEmpresas";
	}
	
	@RequestMapping(value = "/validarEmpresa", method = {RequestMethod.POST})
	public void validarEmpresa(HttpServletResponse response,
			@RequestParam String redEmpresaNit,
			@RequestParam String redEmpresaRegistro){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<Object[]> list = DBContext.getRedEmpresasDao().findEmpresaByNit(redEmpresaNit);
			if(list.size()>0)
				result.put("validate", true);
			else
				result.put("validate", false);
				
			result.put(SUCCESS, true);
			result.put(MESSAGE, "Validado");
		} catch (WebException e) {
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/buscarEmpresas", method = {RequestMethod.GET, RequestMethod.POST})
	public void buscarEmpresas(HttpServletResponse response,
			@RequestParam(required = false) int opcion, 
			@RequestParam(required = false) String estado,
			@RequestParam(required = false) String nombreComercial
			){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			CustomUser cu = WebUtilidades.getCustomUserFromAcegi();;
			result.put("empresas", JSONArray.fromObject(
					DBContext.getRedEmpresasDao().findEmpresaByCriterios(opcion, estado, nombreComercial,cu,new Long(0))));
		}catch (Exception e) {
			logger.error(e);
		}
		serializeObject(result, response);
	}
	
	public String abrirEmpresa(HttpServletRequest request, ModelMap model,
			@RequestParam (value = "redEmpresaFolio") Long redEmpresaFolio){
		return "";
	}
	
	@RequestMapping(value = "/guardarEmpresa", method = {RequestMethod.GET, RequestMethod.POST})
	public String guardarEmpresa(HttpServletRequest request, ModelMap model,
			@ModelAttribute("redEmpresas") RedEmpresas redEmpresas){
		Map<String, Object> resultado = new HashMap<String, Object>();
		try {
			DBContext.getRedEmpresasService().guardarEmpresa(redEmpresas);
			resultado.put(MESSAGE, "Datos guardados exitosamente");
		} catch (WebException e) {
			logger.error(e);
			model.put(MESSAGE, WebUtilidades.getExceptionMessage(e));
			//return "etapas/gstCliente";
		}catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			model.put(MESSAGE, "Procesamiento Incorrecto");
			//return "etapas/gstCliente";
		}
		model.put(MESSAGE, resultado.get(MESSAGE));
		model.put("redempresaFolio", redEmpresas.getRedEmpresaFolio());
		return "";
	}
			
}
